﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FONCREAGROINTEGRAL.Models;
using Microsoft.Reporting.WebForms;

namespace FONCREAGROINTEGRAL.Controllers
{
    
    public class planillaController : Controller
    {
        public SistIntFoncreagroEntities entidades = new SistIntFoncreagroEntities();

        //
        // GET: /planilla/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Areas(int id,int id1)
        {
            string personal = Convert.ToString(Request.QueryString["query"]);

            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);


            if (!String.IsNullOrEmpty(personal))
            {
                var query = entidades.RPlanillaAreas_Result1(id, id1).Where(a => (a.Personal).ToUpper().Contains(personal.ToUpper()))/*.Skip(start).Take(limit)*/.ToList();
                return Json(new { grid = query, total = query.Count() }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var query = entidades.RPlanillaAreas_Result1(id, id1)/*.Skip(start).Take(limit)*/.ToList();
                return Json(new { grid = query, total = query.Count() }, JsonRequestBehavior.AllowGet);
            }
        }
        //planilla/LlenarPlanillaContable
        //id -- IdEjercicioMes
        //id1   --  Id
        public ActionResult LlenarPlanillaContable(int id)
        {
            try
            {
                entidades.RLLENARBOLETACONTABLE(id, 0);
                return Content("OK");
            }
            catch 
            {
                return Content("ERROR");
            }
        }
        //planilla/PagarPlanilla
        //id -- IdEjercicioMes
        //id1   --  Id
        public ActionResult PagarPlanilla(int id)
        {
            string strResponse = String.Empty;
            DateTime Fecha = Convert.ToDateTime(Request.Form["Fecha"]);
            try
            {
                var query = entidades.EJERCICIOMES.Single(em => em.idejerciciomes == id);
                int mes = Convert.ToInt32(query.mes);
                if (mes == Fecha.Month)
                {
                    entidades.RPAGARBOLETACONTABLE(id, 3, Fecha);
                    entidades.RPAGARBOLETACONTABLE(id, 2, Fecha);

                    entidades.RLLENARBOLETACONTABLE(id, 1);
                    entidades.RPAGARPLANILLA(1);

                    strResponse = "{success: true,msg:'Planilla Pagada Correctamente'}";
                    return Content(strResponse);
                }

                //entidades.RPAGARPLANILLA(id);
                strResponse = "{success: false,msg:'Fecha de Cambio no Corresponde a Mes Vigente'}";
                return Content(strResponse);
            }
            catch
            {
                strResponse = "{success: false,msg:'Fallo en la Creación'}";
                return Content(strResponse);
            }
        }


        public ActionResult RevertirPlanilla(int id)
        {
            string strResponse = String.Empty;
            //DateTime Fecha = Convert.ToDateTime(Request.Form["Fecha"]);
            try
            {
                var query = entidades.EJERCICIOMES.Single(em => em.idejerciciomes == id);
                //int mes = Convert.ToInt32(query.mes);
                //if (mes == Fecha.Month)
                //{
                entidades.RH_RevertirPlanillas(id);

                strResponse = "{success: true,msg:'Planilla Revertida Correctamente'}";
                return Content(strResponse);
                //}
                //strResponse = "{success: false,msg:'Fecha de Cambio no Corresponde a Mes Vigente'}";
                //return Content(strResponse);
            }
            catch
            {
                strResponse = "{success: false,msg:'Fallo en la Reversión'}";
                return Content(strResponse);
            }
        }
        //planilla/CerraMes
        //id -- IdEjercicioMes
        //Debe realizar al momento de Confirmar en Contabilidad
        public ActionResult CerraMes(int id)
        {
            try
            {
                entidades.RLLENARBOLETACONTABLE(id, 1);
                entidades.RPAGARPLANILLA(id);

                return Content("OK");
            }
            catch
            {
                return Content("ERROR");
            }
        }
        //id ==== idejerciciomes
        public ActionResult ReportAreas(int id, int id1)
        {
            try
            {
                var eme = entidades.EJERCICIOMES.Single(em => em.idejerciciomes == id);

                //if (eme.estadoP == true)
                //{
                LocalReport localReport = new LocalReport();

                localReport.ReportPath = Server.MapPath("~/Content/Reportes/RPlanillaAreas.rdlc");
                ReportDataSource reportDataSource = new ReportDataSource("RPlanillaAreas", entidades.RPlanillaAreas(id,id1).ToList());

                localReport.DataSources.Add(reportDataSource);
                string reportType = "EXCEL";
                string mimeType;
                string encoding;
                string fileNameExtension;
                string deviceInfo =
                 "<DeviceInfo>" +
              "  <OutputFormat>EXCEL</OutputFormat>" +
              "  <PageWidth>8.27in</PageWidth>" +
              "  <PageHeight>5.83in</PageHeight>" +
              "  <MarginTop>0in</MarginTop>" +
              "  <MarginLeft>0in</MarginLeft>" +
              "  <MarginRight>0in</MarginRight>" +
              "  <MarginBottom>0in</MarginBottom>" +
              "</DeviceInfo>";
                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes;
                renderedBytes = localReport.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=Reportepersona." + fileNameExtension);
                Response.BinaryWrite(renderedBytes);
                Response.End();
                return File(renderedBytes, mimeType);
                //}
                //else
                //{
                //    return Content("1");
                //}
                //return Content("OK");
            }
            catch
            {
                return Content("0");
            }
            //0 error
            //1 mes aun no pagado
        }
        //id ==== idejerciciomes
        public ActionResult RHAFPAreas(int id, int id1)
        {
            try
            {
                var eme = entidades.EJERCICIOMES.Single(em => em.idejerciciomes == id);

                //if (eme.estadoP == true)
                //{
                LocalReport localReport = new LocalReport();

                localReport.ReportPath = Server.MapPath("~/Content/Reportes/RHAFPAreas.rdlc");
                ReportDataSource reportDataSource = new ReportDataSource("RHAFPAreas", entidades.RPlanillaAreas(id, id1).ToList());

                localReport.DataSources.Add(reportDataSource);
                string reportType = "EXCEL";
                string mimeType;
                string encoding;
                string fileNameExtension;
                string deviceInfo =
                 "<DeviceInfo>" +
              "  <OutputFormat>EXCEL</OutputFormat>" +
              "  <PageWidth>8.27in</PageWidth>" +
              "  <PageHeight>5.83in</PageHeight>" +
              "  <MarginTop>0in</MarginTop>" +
              "  <MarginLeft>0in</MarginLeft>" +
              "  <MarginRight>0in</MarginRight>" +
              "  <MarginBottom>0in</MarginBottom>" +
              "</DeviceInfo>";
                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes;
                renderedBytes = localReport.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=Reportepersona." + fileNameExtension);
                Response.BinaryWrite(renderedBytes);
                Response.End();
                return File(renderedBytes, mimeType);
                //}
                //else
                //{
                //    return Content("1");
                //}
                //return Content("OK");
            }
            catch
            {
                return Content("0");
            }
            //0 error
            //1 mes aun no pagado
        }



        public ActionResult liquidacion_certrentquin(int id)
        {
            entidades.RHCalculoLiquidacion(id);
            var periodoLaboral = entidades.PERIODOLABORALs.SingleOrDefault(cc=>cc.IdPeriodoLaboral == id);
            string PersonaId = periodoLaboral.IdPersonal.ToString();
            var ejercicioMes = entidades.EJERCICIOMES.SingleOrDefault(cc=>cc.vigente==true);
            string IdEjercicio = ejercicioMes.IdEjercicio.ToString();
            string strResponse = String.Empty;
            try
            {
                LocalReport localReport = new LocalReport();
                localReport.ReportPath = Server.MapPath("~/Content/Reportes/RCERTRENTAQUINTA.rdlc");
                System.Data.Objects.ObjectResult<FONCREAGROINTEGRAL.Models.PARepCertRentaQuintaAnual_Result> data = entidades.PARepCertRentaQuintaAnual(Int32.Parse(IdEjercicio), Int32.Parse(PersonaId));
                ReportDataSource reportDataSource = new ReportDataSource("PARepCertRentaQuintaAnual", data);
                localReport.DataSources.Add(reportDataSource);
                string reportType = "PDF";
                string mimeType;
                string encoding;
                string fileNameExtension;
                string deviceInfo =
                 "<DeviceInfo>" +
              "  <OutputFormat>PDF</OutputFormat>" +
              "</DeviceInfo>";
                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes;
                renderedBytes = localReport.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=Reporte_CertificadoQuinta." + fileNameExtension);
                Response.BinaryWrite(renderedBytes);
                Response.End();
                return File(renderedBytes, mimeType);

            }
            catch
            {
                return Content("0");


            }
        }
    }
}
